package com.tao.common

import android.content.res.Configuration

/**
 *
 * 类描述: 作为组件生命周期初始化的配置类,通过反射机制,动态调用每个组件初始化逻辑
 *
 */
class ModuleManager private constructor() {

    private var moduleNames = arrayOf(SOUTH_APP, NORTH_APP)
    private var modules = mutableListOf<ModuleSource>()

    init {
        // 初始化app
        for (name in moduleNames) {
            try {
                val clazz = Class.forName(name)
                modules.add(clazz.newInstance() as ModuleSource)
            } catch (e: ClassNotFoundException) {
                e.printStackTrace()
            } catch (e: InstantiationException) {
                e.printStackTrace()
            } catch (e: IllegalAccessException) {
                e.printStackTrace()
            }
        }
    }

    private object SingleHolder {
        val instance = ModuleManager()
    }

    fun onCreate() {
        for (module in modules) {
            module.onCreate()
        }
    }

    fun onLowMemory() {
        for (module in modules) {
            module.onLowMemory()
        }
    }

    fun onConfigurationChanged(newConfig: Configuration) {
        for (module in modules) {
            module.onConfigurationChanged(newConfig)
        }
    }

    companion object {
        val instance: ModuleManager
            get() = SingleHolder.instance

        // 类描述: 组件生命周期初始化类的类目管理者,在这里注册需要初始化的组件,通过反射动态调用各个组件的初始化方法
        private const val SOUTH_APP = "com.tao.south.SouthModule"
        private const val NORTH_APP = "com.tao.north.NorthModule"
    }
}